//
//  XJ_Utils.m
//  XunJieProject
//
//  Created by 薛子 on 2018/6/7.
//  Copyright © 2018年 Soowin. All rights reserved.
//

#import "XJ_Utils.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "sys/utsname.h"
#import "AFHTTPSessionManager.h"
#import "ZDXAlertView.h"
#define openHttps NO

#define iOS7_or_Later ([[UIDevice currentDevice] systemVersion].floatValue >= 7.0 ? YES : NO)

static MBProgressHUD *HUD;

@implementation XJ_Utils
+ (void)POSTZDX:(NSString *)url parameters:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    [XJ_Utils hideHUD];
    [XJ_Utils showHUD];
    
    [XJ_Utils monitorNetworking];
    ////判断是否有网络
    NSString *isNetwork =[[NSUserDefaults standardUserDefaults] objectForKey:@"isNetwork"];
    if (![isNetwork isEqualToString:@"1"]) {//没有网络 不请求数据
         [XJ_Utils hideHUD];
        return;
    }
    
    
    url = [NSString stringWithFormat:@"%@%@",HOSTURL,url];
    if ([params count]) {
        
        NSString * paramString = [XJ_Utils urlWithSignValue3:params];
        
        url = [NSString stringWithFormat:@"%@%@",url,paramString];
        
    }
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 60.f;
   
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript",@"text/plain", nil];
    
//    NSString*header=[self requestHeaderEncryption:nil Url:url];
    //封装入请求头
    [manager.requestSerializer setValue:@"text/html;charset=urf-8" forHTTPHeaderField:@"X-Content-Type"];
    
   
    
    
    
    [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        // 传输进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]] || [responseObject isKindOfClass:[NSDictionary class]]) {
            success(responseObject);
        } else {
            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);
            id response=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            
            success([NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
    }];
    
    
    
}

+(BOOL)post:(NSString *)urlStr  parameters:(NSDictionary *)parameters success:( void(^)(NSInteger recode, id jsonObject) ) success failure:( void(^)(NSInteger recode, NSError *error) ) failure
{
    [XJ_Utils hideHUD];
    [XJ_Utils showHUD];
    
    
    [XJ_Utils monitorNetworking];
    ////判断是否有网络
    NSString *isNetwork =[[NSUserDefaults standardUserDefaults] objectForKey:@"isNetwork"];
    if (![isNetwork isEqualToString:@"1"]) {//没有网络 不请求数据
         [XJ_Utils hideHUD];
        return NO;
    }
    
    urlStr = [NSString stringWithFormat:@"%@%@",HOSTURL,urlStr];
    if ([parameters count]) {
        
        NSString * paramString = [XJ_Utils urlWithSignValue3:parameters];
        
        urlStr = [NSString stringWithFormat:@"%@%@",urlStr,paramString];

    }
    
    NSAssert(urlStr != nil, @"ruquest address cannot be nil");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    AFHTTPSessionManager * _sessionManager = [AFHTTPSessionManager manager];
    
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    _sessionManager.requestSerializer.timeoutInterval =60;
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    if (token!=nil &&![token isEqualToString:@""]) {
        _sessionManager.requestSerializer.HTTPShouldHandleCookies=YES;
        [_sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
        
    }
    
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];//app版本
    
    [_sessionManager.requestSerializer setValue:appVersion forHTTPHeaderField:@"app-ver"];
    [_sessionManager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"device"];
    [_sessionManager.requestSerializer setValue:@"text/html;charset=urf-8" forHTTPHeaderField:@"Content_Type"];
    
    
    AFJSONResponseSerializer *jsonResponse = [AFJSONResponseSerializer serializer];
    _sessionManager.responseSerializer = jsonResponse;
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    
    
    [_sessionManager POST:urlStr parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [XJ_Utils hideHUD];
        NSDictionary * dict = (NSDictionary *)responseObject;
        NSLog(@"*** dict = %@",dict);
        
        NSString * recode = [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]];
        
        if (![recode isEqualToString:@"200"]) {
            
            if ([recode isEqualToString:@"124"]) {
                
              
                
                NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
                [db setObject:@"" forKey:@"token"];
                [db synchronize];
                
                 [(AppDelegate*)[UIApplication sharedApplication].delegate crearRootLoginController];
                
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"登录失效,请重新登录！" image:@"pop_msg_error_xs"];
                [alext showXLAlertView];
                
            }else{
                
                [XJ_Utils alertViewWithMessage:[dict objectForKey:@"msg"]];
            }
            
            NSLog(@"------ error message ----- error method :%@,%@",recode,[dict objectForKey:@"msg"]);
            
            return;
        }
        success([recode integerValue],responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [XJ_Utils hideHUD];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"----- error message:%@",[error localizedDescription]);
        if (failure) {
            failure(0,error);
        }
    }];
    
    return YES;
}

+(BOOL)signPost:(NSString *)urlStr  parameters:(NSDictionary *)parameters success:( void(^)(NSInteger recode, id jsonObject) ) success failure:( void(^)(NSInteger recode, NSError *error) ) failure
{
    [XJ_Utils hideHUD];
    [XJ_Utils showHUD];
    
    [XJ_Utils monitorNetworking];
    ////判断是否有网络
    NSString *isNetwork =[[NSUserDefaults standardUserDefaults] objectForKey:@"isNetwork"];
    if (![isNetwork isEqualToString:@"1"]) {//没有网络 不请求数据
         [XJ_Utils hideHUD];
        return NO;
    }
    
    urlStr = [NSString stringWithFormat:@"%@%@",HOSTURL,urlStr];
    if ([parameters count]) {
        
        NSString * paramString = [XJ_Utils urlWithSignValue2:parameters];
        
        NSString * signString = [XJ_Utils urlWithSignValue:parameters];
        
        urlStr = [NSString stringWithFormat:@"%@%@sign=%@",urlStr,paramString,[signString uppercaseString]];
        
    }
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"urlStr = %@",urlStr);
    
    NSAssert(urlStr != nil, @"ruquest address cannot be nil");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    AFHTTPSessionManager * _sessionManager = [AFHTTPSessionManager manager];
    
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    _sessionManager.requestSerializer.timeoutInterval =60;
    
    
    
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];//app版本
    
    [_sessionManager.requestSerializer setValue:appVersion forHTTPHeaderField:@"app-ver"];
    [_sessionManager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"device"];
    [_sessionManager.requestSerializer setValue:@"text/html;charset=urf-8" forHTTPHeaderField:@"Content_Type"];
    
    
    AFJSONResponseSerializer *jsonResponse = [AFJSONResponseSerializer serializer];
    _sessionManager.responseSerializer = jsonResponse;
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    
//    AFHTTPRequestSerializer *request = [AFHTTPRequestSerializer serializer];
//
//    _sessionManager.requestSerializer = request;
    _sessionManager.responseSerializer = [AFJSONResponseSerializer  serializer];
    
    
    
    [_sessionManager POST:urlStr parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [XJ_Utils hideHUD];
        NSDictionary * dict = (NSDictionary *)responseObject;
        NSLog(@"*** dict = %@",dict);
        
        NSString * recode = [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]];
        
        if (![recode isEqualToString:@"200"]) {
            
            if ([recode isEqualToString:@"124"]) {
                
                
                
                NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
                [db setObject:@"" forKey:@"token"];
                [db synchronize];
                
                [(AppDelegate*)[UIApplication sharedApplication].delegate crearRootLoginController];
                
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"登录失效,请重新登录！" image:@"pop_msg_error_xs"];
                [alext showXLAlertView];
                
            }else{
                
                [XJ_Utils alertViewWithMessage:[dict objectForKey:@"msg"]];
            }
            NSLog(@"------ error message ----- error method :%@,%@",recode,[dict objectForKey:@"msg"]);
            
            return;
        }
        success([recode integerValue],responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [XJ_Utils hideHUD];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"----- error message:%@",[error localizedDescription]);
        if (failure) {
            failure(0,error);
        }
        
        NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (data) {
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"服务器的错误原因:%@",str);
            
            id response=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            //        [XJ_Utils alertViewWithMessage:[response objectForKey:@"msg"]];
            
            ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:[response objectForKey:@"msg"] image:@"pop_msg_tip_xs"];
            [alext showXLAlertView];
        }
        
        
        

        
    }];
    
    return YES;
}

+(BOOL)imagePost:(NSString *)urlStr  parameters:(NSDictionary *)parameters image:(UIImage *)image success:( void(^)(NSInteger recode, id jsonObject) ) success failure:( void(^)(NSInteger recode, NSError *error) ) failure{
    
    [XJ_Utils hideHUD];
    [XJ_Utils showHUD];
    
    
    [XJ_Utils monitorNetworking];
    ////判断是否有网络
    NSString *isNetwork =[[NSUserDefaults standardUserDefaults] objectForKey:@"isNetwork"];
    if (![isNetwork isEqualToString:@"1"]) {//没有网络 不请求数据
         [XJ_Utils hideHUD];
        return NO;
    }
    
    urlStr = [NSString stringWithFormat:@"%@%@",HOSTURL,urlStr];
    if ([parameters count]) {
        
        NSString * paramString = [XJ_Utils urlWithSignValue2:parameters];
        
        NSString * signString = [XJ_Utils urlWithSignValue:parameters];
        
        urlStr = [NSString stringWithFormat:@"%@%@sign=%@",urlStr,paramString,[signString uppercaseString]];
        
    }
    
    NSAssert(urlStr != nil, @"ruquest address cannot be nil");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    AFHTTPSessionManager * _sessionManager = [AFHTTPSessionManager manager];
    
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    _sessionManager.requestSerializer.timeoutInterval =60;
    
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];//app版本
    
    [_sessionManager.requestSerializer setValue:appVersion forHTTPHeaderField:@"app-ver"];
    [_sessionManager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"device"];
    [_sessionManager.requestSerializer setValue:@"text/html;charset=urf-8" forHTTPHeaderField:@"Content_Type"];
    
    
    AFJSONResponseSerializer *jsonResponse = [AFJSONResponseSerializer serializer];
    _sessionManager.responseSerializer = jsonResponse;
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    
    
//    [_sessionManager POST:urlStr parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//        [XJ_Utils hideHUD];
//        NSDictionary * dict = (NSDictionary *)responseObject;
//        NSLog(@"*** dict = %@",dict);
//
//        NSString * recode = [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]];
//
//        if (![recode isEqualToString:@"200"]) {
//
//            [XJ_Utils alertViewWithMessage:[dict objectForKey:@"msg"]];
//            NSLog(@"------ error message ----- error method :%@,%@",recode,[dict objectForKey:@"msg"]);
//
//            return;
//        }
//        success([recode integerValue],responseObject);
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [XJ_Utils hideHUD];
//        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//        NSLog(@"----- error message:%@",[error localizedDescription]);
//        if (failure) {
//            failure(0,error);
//        }
//    }];
    

    [_sessionManager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
        NSString *filename = @"/this/is/my/file/name";
        [imageData writeToFile: filename atomically: NO];
        NSString *name = @"photo.jpg";
        NSString *type = @"image/jpeg";
        
        if (imageData != nil) {

            [formData appendPartWithFileData:imageData name:@"file" fileName:name mimeType:type];
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [XJ_Utils hideHUD];
        NSDictionary * dict = (NSDictionary *)responseObject;
        NSLog(@"*** dict = %@",dict);
        
        NSString * recode = [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]];
        
        if (![recode isEqualToString:@"200"]) {
            
            if ([recode isEqualToString:@"124"]) {
                
               
                
                NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
                [db setObject:@"" forKey:@"token"];
                [db synchronize];
                
                [(AppDelegate*)[UIApplication sharedApplication].delegate crearRootLoginController];
                
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"登录失效,请重新登录！" image:@"pop_msg_error_xs"];
                [alext showXLAlertView];
                
            }else{
                
                [XJ_Utils alertViewWithMessage:[dict objectForKey:@"msg"]];
            }
            NSLog(@"------ error message ----- error method :%@,%@",recode,[dict objectForKey:@"msg"]);
            
            return;
        }
        success([recode integerValue],responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [XJ_Utils hideHUD];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"----- error message:%@",[error localizedDescription]);
        if (failure) {
            failure(0,error);
        }
        
    }];
    
    
    return YES;
}

+(BOOL)get:(NSString *)urlStr  parameters:(NSDictionary *)parameters success:( void(^)(NSInteger recode, id jsonObject) ) success failure:( void(^)(NSInteger recode, NSError *error) ) failure{
    
    [XJ_Utils hideHUD];
    [XJ_Utils showHUD];
    
    [XJ_Utils monitorNetworking];
    ////判断是否有网络
    NSString *isNetwork =[[NSUserDefaults standardUserDefaults] objectForKey:@"isNetwork"];
    if (![isNetwork isEqualToString:@"1"]) {//没有网络 不请求数据
         [XJ_Utils hideHUD];
        return NO;
    }

    urlStr = [NSString stringWithFormat:@"%@%@",HOSTURL,urlStr];
    
    if ([parameters count]) {
        
        NSString * paramString = [XJ_Utils urlWithSignValue3:parameters];
        
        urlStr = [NSString stringWithFormat:@"%@%@",urlStr,paramString];
        
    }
    
    NSAssert(urlStr != nil, @"ruquest address cannot be nil");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    AFHTTPSessionManager * _sessionManager = [AFHTTPSessionManager manager];
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    _sessionManager.requestSerializer.timeoutInterval =60;
    _sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];

    _sessionManager.requestSerializer.HTTPShouldHandleCookies=YES;
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    if (token!=nil &&![token isEqualToString:@""]) {
        _sessionManager.requestSerializer.HTTPShouldHandleCookies=YES;
        [_sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
        
    }
    
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];//app版本
    
    [_sessionManager.requestSerializer setValue:appVersion forHTTPHeaderField:@"app-ver"];
    [_sessionManager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"device"];
    [_sessionManager.requestSerializer setValue:@"text/html;charset=urf-8" forHTTPHeaderField:@"Content_Type"];
    
    
    AFJSONResponseSerializer *jsonResponse = [AFJSONResponseSerializer serializer];
    _sessionManager.responseSerializer = jsonResponse;
   _sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg", nil];
    
    [_sessionManager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [XJ_Utils hideHUD];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        NSDictionary * dict = (NSDictionary *)responseObject;
        NSLog(@"*** dict = %@",dict);
    

//        NSString * recode = [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]];
//
//        if (![recode isEqualToString:@"200"]) {
//
//        [XJ_Utils alertViewWithMessage:[dict objectForKey:@"msg"]];
//        NSLog(@"------ error message :%@",[dict objectForKey:@"msg"]);
//        return ;
//        }
//
//        success([recode integerValue],responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [XJ_Utils hideHUD];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"----- error message:%@",[error localizedDescription]);

        if (failure) {
            failure(0,error);
        }
    }];
    
    return YES;
}




+(void)showHUD
{
    AppDelegate *delegat = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    UIWindow *window = [delegat window];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if ([[self getCurrentVC] isKindOfClass:[UIViewController class]]) {
            //            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self getCurrentVC].view animated:YES];
            
            MBProgressHUD *hud =[MBProgressHUD showMessage:@"" toView:[self getCurrentVC].view];
            
            //            hud.backgroundColor = [UIColor clearColor];
            
            
            //[UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = [UIColor blueColor];
            HUD = hud;
        }else {
            //            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
            MBProgressHUD *hud =[MBProgressHUD showMessage:@"" toView:window];
            HUD = hud;
        }
        
        
        
    });
}

+(void)hideHUD
{
    
    //    HUD.mode = MBProgressHUDModeIndeterminate;
    
    //HUD.labelText = @"加载完成";
    [HUD hide:YES afterDelay:0.0];
    dispatch_async(dispatch_get_main_queue(), ^{
        [HUD removeFromSuperview];
    });
    
    HUD = nil;
}
//获取当前屏幕显示的viewcontroller
+ (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        
        UIViewController *vc = appRootVC.presentedViewController;
        if (vc.presentedViewController){
            
            while (vc.presentedViewController){
                vc = vc.presentedViewController;
            }
            nextResponder = vc;
        }
        
        
        //nextResponder = appRootVC.presentedViewController;
    }else{
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    
    return result;
}

+ (NSMutableDictionary *)completeParameterWith:(NSMutableDictionary *)originalParameter{
//        NSString *transactionId = [XJ_Utils getTransactionId];
//        NSString *timestamp = [NSString stringWithFormat:@"%ld",time(NULL)];
//        [originalParameter setObject:@"utf-8" forKey:@"inputcharset"];
//        [originalParameter setObject:@"MD5" forKey:@"signmethod"];
//        [originalParameter setObject:timestamp forKey:@"timestamp"];
//        [originalParameter setObject:transactionId forKey:@"transactionid"];
//        [originalParameter setObject:[XJ_Utils urlWithSignValue:originalParameter] forKey:@"sign"];
    
    return originalParameter;
}
//sign字符串
+ (NSString *)urlWithSignValue:(NSDictionary*)dict
{
    NSMutableString *str = [NSMutableString stringWithCapacity:0];
    NSArray *array = [[dict allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    for (int i=0; i<[array count]; i++) {
        NSString *key = [array objectAtIndex:i];
        NSString *value = [NSString stringWithFormat:@"%@",[dict valueForKey:key]];
        if (value && value.length > 0) {
            [str appendString:[NSString stringWithFormat:@"%@=%@",[key lowercaseString], [value lowercaseString]]];
        }
    }
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSString * temp = [NSString stringWithFormat:@"%@%@",str,[token lowercaseString]];
    
    
    NSString *signValue = [temp md5HexDigest];
    
    return signValue;
}


//字符串
+ (NSString *)urlWithSignValue2:(NSDictionary*)dict
{
    NSMutableString *str = [NSMutableString stringWithCapacity:0];
    NSArray *array = [[dict allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    for (int i=0; i<[array count]; i++) {
        NSString *key = [array objectAtIndex:i];
        NSString *value = [NSString stringWithFormat:@"%@",[dict valueForKey:key]];
        if (value && value.length > 0) {
            [str appendString:[NSString stringWithFormat:@"%@=%@%@", key, value,@"&"]];
        }
    }
    return str;
}

//字符串
+ (NSString *)urlWithSignValue3:(NSDictionary*)dict
{
    NSMutableString *str = [NSMutableString stringWithCapacity:0];
    NSArray *array = [[dict allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    for (int i=0; i<[array count]; i++) {
        NSString *key = [array objectAtIndex:i];
        NSString *value = [NSString stringWithFormat:@"%@",[dict valueForKey:key]];
        if (value && value.length > 0) {
            [str appendString:[NSString stringWithFormat:@"%@=%@%@", key, value,(i != [array count]-1 ? @"&" : @"")]];
        }
    }
    return str;
}

+ (void)alertViewWithMessage:(NSString *)message{
    UIAlertView * view  = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [view show];
}

+ (NSString *)MD5EncryptWith:(NSString *)originalStr{
    if (originalStr.length == 0) {
        return nil;
    }
    
    originalStr = [originalStr md5HexDigest];
    originalStr = [originalStr lowercaseString];
    originalStr = [originalStr md5HexDigest];
    originalStr = [originalStr uppercaseString];
    return originalStr;
}

+ (NSString *)getTransactionId{
    
    NSMutableString * originalStr = [NSMutableString stringWithString:[[NSUUID UUID] UUIDString]];
    [originalStr replaceOccurrencesOfString:@"-" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [originalStr length])];
    
    return [originalStr lowercaseString];
}

+ (NSString *)getTimeFromTimestamp:(NSString *)timeStampString
{
    if (timeStampString.length == 0) {
        
        return nil ;
    }
    // iOS 生成的时间戳是10位
    NSTimeInterval interval    =[timeStampString doubleValue];
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate: date];
    
    return dateString;
}
#pragma mark- 获取手机型号
+ (NSString*)deviceString
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    return deviceString;
}

+(CGSize)labelSizeWithStr:(NSString *)str andHeight:(CGFloat)height andFont:(CGFloat)font{
    
    CGSize oriSize = CGSizeMake(10000, height);
    
    CGSize size = [str boundingRectWithSize:oriSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return size;
}
+(CGSize )labelSizeWithStr:(NSString *)str andWight:(CGFloat)wight andFont:(CGFloat)font{
    
    CGSize oriSize = CGSizeMake(wight, 10000);
    
    CGSize size = [str boundingRectWithSize:oriSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return size;
}
+ (NSString *)getStringByDate:(NSDate *)date{
    if (date == nil) {
        return nil;
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate:date];
    return currentDateStr;
}

+(int)compareOneDay:(NSString *)oneDay withAnotherDay:(NSString *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *dateA = [dateFormatter dateFromString:oneDay];
    NSDate *dateB = [dateFormatter dateFromString:anotherDay];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}

#pragma mark - ------------- 监测网络状态 -------------
+(void)monitorNetworking
{
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:
                NSLog(@"未知网络");
                break;
            case 0:
                NSLog(@"网络不可达");
                break;
            case 1:
            {
                NSLog(@"GPRS网络");
            }
                break;
            case 2:
            {
                NSLog(@"wifi网络");
            }
                break;
            default:
                break;
        }
        if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
            NSLog(@"有网");
            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isNetwork"];
        }else{
            NSLog(@"没网");
            dispatch_async(dispatch_get_main_queue(), ^{
                //            //inset code....
                [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"isNetwork"];
                NSString *message =@"网络连接失败，请稍后再试！";
                
                ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:message image:@"pop_msg_tip_xs"];
                [alext showXLAlertView];
            });
            
            
        }
    }];
    
}

@end
